﻿using System;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem.UI;
using UnityEngine.UI;

public class TemporaryUI : MonoBehaviour
{
    [SerializeField] Button btnStartHost;
    [SerializeField] Button btnStartClient;
    [SerializeField] Button btnStopHostOrClient;

    [SerializeField] Text txtPosition;


    private TilemapManager tm;

    private void Awake()
    {
        // 自动创建事件系统
        if (!FindAnyObjectByType<EventSystem>())
        {
            Type inputType = typeof(InputSystemUIInputModule);
            GameObject eventSystem = new("EventSystem", typeof(EventSystem), inputType);
            eventSystem.transform.SetParent(transform);
        }
    }

    private void Start()
    {
        tm = FindFirstObjectByType<TilemapManager>();

        btnStartHost.onClick.AddListener(StartHost);
        btnStartClient.onClick.AddListener(StartClient);
        btnStopHostOrClient.onClick.AddListener(StopHostOrClient);

        SetButtonStates(false);

        // 当客户端断开连接时（在每个客户端调用）
        NetworkManager.Singleton.OnClientStopped += (bool bb) =>
        {
            SetButtonStates(false);
            tm.ClearAllTiles();
        };
    }

    private void Update()
    {
    }

    private void StartClient()
    {
        if (NetworkManager.Singleton.StartClient())
        {
            SetButtonStates(true);
        }
    }

    private void StartHost()
    {
        if (NetworkManager.Singleton.StartHost())
        {
            SetButtonStates(true);
        }
    }

    private void StopHostOrClient()
    {
        NetworkManager.Singleton.Shutdown();
    }

    private void SetButtonStates(bool isGaming)
    {
        btnStartHost.interactable = !isGaming;
        btnStartClient.interactable = !isGaming;
        btnStopHostOrClient.interactable = isGaming;
    }

    public void UpdatePosition(Vector3 position)
    {
        int x = Convert.ToInt32(position.x);
        int y = Convert.ToInt32(position.y);
        txtPosition.text = $"{x},{y}";
    }
}